package com.kfm.base.it;

public class Dog implements Cloneable {

    private String name;

    private String color;

    public Dog() {
    }

    public Dog(String name, String color) {
        this.name = name;
        this.color = color;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", color='" + color + '\'' +
                '}';
    }

    @Override
    public Dog clone() throws CloneNotSupportedException {
        return (Dog) super.clone();
    }
}

class Person implements Cloneable {
    private String name;

    private int age;

    private Dog dog;

    public Person(String name, int age, Dog dog) {
        this.name = name;
        this.age = age;
        this.dog = dog;
    }

    public Dog getDog() {
        return dog;
    }

    /**
     * 克隆
     * 浅克隆, 对象中的引用数据类型的字段是同一个引用 [默认]
     * 深克隆，将对象中的引用数据类型也复制一份
     * @return
     * @throws CloneNotSupportedException
     */
    @Override
    protected Person clone() throws CloneNotSupportedException {
//        return (Person) super.clone();
        Person copy = (Person) super.clone();
        // 将引用数据类型 clone 一份， 再设置
        Dog copyDog = copy.getDog().clone();
        copy.dog = copyDog;

        return copy;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", dog=" + dog +
                '}';
    }
}

class CloneTest {

    public static void main(String[] args) throws CloneNotSupportedException {
        Dog dog = new Dog("旺财", "黑色");

        Person person = new Person("赵文翔", 22, dog);

        System.out.println(person);

        Person copy = person.clone();
        System.out.println(copy);

        System.out.println(person.getDog() == copy.getDog());

        person.getDog().setName("富贵");

        System.out.println(person);
        System.out.println(copy);

    }
}
